<template>
  <div class="role">
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片式图 -->
    <el-card>
      <el-row>
        <el-col
          ><el-button type="primary" @click="addRoleVisible = true"
            >添加角色</el-button
          ></el-col
        >
      </el-row>
      <!-- 角色列表 -->
      <el-table :data="roleList" style="width: 100%" border stripe>
        <!-- 展开权限列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              class="borBottom vcenter"
              :class="i1 == 0 ? 'borTop' : ''"
              v-for="(item, i1) in scope.row.children"
              :key="item.id"
            >
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="removeRight(scope.row, item.id)">{{
                  item.authName
                }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级权限、三级权限 -->
              <el-col :span="19">
                <el-row
                  :class="i2 ? 'borTop' : ''"
                  v-for="(subItem1, i2) in item.children"
                  :key="subItem1.id"
                >
                  <el-col :span="6">
                    <!-- 二级权限 -->
                    <el-tag
                      closable
                      type="success"
                      @close="removeRight(scope.row, subItem1.id)"
                      >{{ subItem1.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <!-- 三级权限 -->
                    <el-tag
                      type="warning"
                      closable
                      v-for="subItem2 in subItem1.children"
                      :key="subItem2.id"
                      @close="removeRight(scope.row, subItem2.id)"
                      >{{ subItem2.authName }}</el-tag
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index" width="50"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
        <el-table-column label="操作" width="285">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showEditDialog(scope.row.id)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="delRole(scope.row.id)"
              >删除</el-button
            >
            <el-button
              type="warning"
              icon="el-icon-setting"
              size="mini"
              @click="showSetRigthDialog(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加角色对话框 -->
    <el-dialog title="添加角色" :visible.sync="addRoleVisible" width="50%">
      <el-form
        :model="addRoleForm"
        :rules="rules"
        ref="addFormRef"
        @close="formClosed"
      >
        <el-form-item
          label="角色名称"
          :label-width="formLabelWidth"
          prop="roleName"
        >
          <el-input
            v-model="addRoleForm.roleName"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="角色描述"
          :label-width="formLabelWidth"
          prop="roleDesc"
        >
          <el-input
            v-model="addRoleForm.roleDesc"
            autocomplete="off"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addRoleVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRole">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改角色对话框 -->
    <el-dialog title="修改角色" :visible.sync="editRoleVisible" width="50%">
      <el-form
        :model="editRoleForm"
        :rules="rules"
        ref="editFormRef"
        @close="formClosed"
      >
        <el-form-item
          label="角色名称"
          :label-width="formLabelWidth"
          prop="roleName"
        >
          <el-input
            v-model="editRoleForm.roleName"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="角色描述"
          :label-width="formLabelWidth"
          prop="roleDesc"
        >
          <el-input
            v-model="editRoleForm.roleDesc"
            autocomplete="off"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editRoleVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRole(editRoleForm.roleId)"
          >确 定</el-button
        >
      </span>
    </el-dialog>

    <!-- 修改角色对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRightVisible"
      width="50%"
      @close="resetDefKeys"
    >
      <!-- 树形控件 -->
      <el-tree
        ref="treeRef"
        :data="rightsList"
        :props="treeProps"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="defKeys"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      roleList: [],
      addRoleVisible: false, //控制添加角色对话框的显示隐藏
      //添加角色表单
      addRoleForm: {
        roleName: "",
        roleDesc: "",
      },
      editRoleVisible: false, //控制修改角色对话框的显示隐藏
      editRoleForm: {}, //修改角色表单
      setRightVisible: false, //控制分配权限对话框的显示隐藏
      roleId:"",//获取需要分配权限的角色id
      rightsList: [], //所有权限的数组
      //树形控件的属性绑定对象
      treeProps: {
        label: "authName",
        children: "children",
      },
      defKeys: [], //默认选中节点的id值数组
      formLabelWidth: "80px", //控制弹窗的宽度
      rules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
        ],
        roleDesc: [
          { required: true, message: "请输入角色描述", trigger: "blur" },
        ],
      },
    };
  },
  mounted() {
    this.getRoleList();
  },
  methods: {
    getRoleList() {
      this.axios.get("roles").then((res) => {
        let result = res.data;
        // console.log(result);
        if (result.meta.status != 200) {
          this.$message.error("获取角色失败");
        } else {
          this.roleList = result.data;
        }
      });
    },
    //添加新的角色
    addRole() {
      this.$refs.addFormRef.validate((valid) => {
        if (!valid) return this.$message.error("请完善添加信息");
        this.axios.post("roles", this.addRoleForm).then((res) => {
          let result = res.data;
          if (result.meta.status != 201)
            return this.$message.error("添加角色失败");
          this.addRoleVisible = false;
          this.getRoleList();
          this.$message.success("添加角色成功");
        });
      });
    },
    //监听对话听关闭，重置表单内容
    formClosed() {
      this.$refs.addFormRef.resetFields();
    },
    //删除角色
    delRole(id) {
      this.$confirm("此操作将永久删除该角色, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.axios.delete(`roles/${id}`).then((res) => {
            let result = res.data;
            if (result.meta.status != 200)
              return this.$message.error("删除失败");
            this.$message.success("删除成功");
            this.getRoleList();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //显示修改用户信息对话框
    showEditDialog(id) {
      this.editRoleVisible = true;
      this.axios.get(`roles/${id}`).then((res) => {
        let result = res.data;
        if (result.meta.status == 200) {
          this.editRoleForm = result.data;
        }
      });
    },
    //修改角色
    editRole(id) {
      this.$refs.editFormRef.validate((valid) => {
        if (!valid) return this.$message.error("请完善修改信息");
        this.axios.put(`roles/${id}`, this.editRoleForm).then((res) => {
          let result = res.data;
          if (result.meta.status != 200) return this.$message.error("修改失败");
          this.editRoleVisible = false;
          this.$message.success("修改成功");
          this.getRoleList();
        });
      });
    },
    //点击删除对应的权限标签
    removeRight(role, rightId) {
      // console.log(roleId);
      // console.log(rightId);
      this.$confirm("此操作将永久删除该权限, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.axios
            .delete(`roles/${role.id}/rights/${rightId}`)
            .then((res) => {
              let result = res.data;
              if (result.meta.status != 200)
                return this.$message.error("删除失败");
              this.$message.success(result.meta.msg);
              // this.getRoleList()
              role.children = result.data;
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //展示分配权限的对话框
    showSetRigthDialog(role) {
      this.roleId = role.id
      this.axios.get("rights/tree").then((res) => {
        let result = res.data;
        if (result.meta.status !== 200)
          return this.$message.error("获取权限列表失败");
        this.rightsList = result.data;
        // console.log(this.rightsList);
        // console.log(role);
        this.getLeafKeys(role, this.defKeys);
        this.setRightVisible = true;
      });
    },
    //通过递归的形式，获取角色下所有三级权限的id，并保存到数组defKeys
    getLeafKeys(node, arr) {
      if (!node.children) {
        return arr.push(node.id);
      }
      node.children.forEach((item) => {
        this.getLeafKeys(item, arr);
      });
    },
    resetDefKeys() {
      this.defKeys = [];
    },
    //点击为角色分配权限
    allotRights() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ];
      // console.log(keys);
      const idStr = keys.join()
      this.axios.post(`roles/${this.roleId}/rights`,{rids:idStr}).then(res=>{
        let result = res.data
        if(result.meta.status !== 200) return this.$message.error("分配权限失败")
        this.$message.success("分配权限成功")
        this.setRightVisible = false
        this.getRoleList()
      })

    },
  },
};
</script>

<style lang="scss" scoped>
.el-row {
  text-align: left;
}
.el-tag {
  margin: 10px;
}
.borTop {
  border-top: 1px solid #ccc;
}
.borBottom {
  border-bottom: 1px solid #ccc;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>